import { NProgressUtil } from '@/utils/nprogress.js';
import { CacheUtil } from '@/utils/cacheUtil.js';
import { ElMessage } from 'element-plus';
import loginUserStore from '@/stores/modules/loginUser.js';
import permissionStore from '@/stores/modules/permission.js';

const whiteList = ['/login'];
export function createRouterGuards(router) {
  router.beforeEach((to, from, next) => {
    NProgressUtil.start();
    if (CacheUtil.getToken()) {
      let title = import.meta.env.VITE_APP_TITLE;
      if (to.meta.title) {
        title = title + '-' + to.meta.title;
      }
      document.title = title;
      if (to.path === '/login') {
        next({path: '/'});
        NProgressUtil.close();
      } else {
        if (loginUserStore().roles.length === 0) {
          loginUserStore().getUserInfo().then(() => {
            permissionStore().generateRoutes().then(accessRoutes => {
              for (const route of accessRoutes) {
                router.addRoute(route);
              }
              next({...to, replace: true});
            }).catch(error => {
              ElMessage.error(error);
              NProgressUtil.close();
            });
          })
        } else {
          next();
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.fullPath}`);
        NProgressUtil.close();
      }
    }
  });
  router.afterEach(() => {
    NProgressUtil.close();
  })
}